package ip

import (
	"gitee.com/injoyai/goutil/string/regexps"
	"io/ioutil"
	"net"
	"net/http"
	"strings"
)

// 本地ip地址
var local string

// IsLocal 是否是局域网ip
func IsLocal() bool { return regexps.IsLAN(GetLocal()) }

// GetLocal 获取本地ip
func GetLocal() string {
	if len(local) == 0 {
		local = getLocal()
	}
	return local
}

func getLocal() string {
	netInterfaces, err := net.Interfaces()
	if err != nil {
		return ""
	}
	ips := []string(nil)
	for i := 0; i < len(netInterfaces); i++ {
		if (netInterfaces[i].Flags & net.FlagUp) != 0 {
			addrs, _ := netInterfaces[i].Addrs()
			for _, address := range addrs {
				if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
					if ipnet.IP.To4() != nil {
						if strings.Contains(ipnet.IP.String(), "192.168.") {
							return ipnet.IP.String()
						}
						ips = append(ips, ipnet.IP.String())
					}
				}
			}
		}
	}
	if len(ips) > 0 {
		return ips[0]
	}
	return ""
}

func GetRemote(r *http.Request) string {
	if len(r.RemoteAddr) == 0 {
		realIps := r.Header.Get("X-Forwarded-For")
		if realIps != "" && len(realIps) != 0 && !strings.EqualFold("unknown", realIps) {
			ipArray := strings.Split(realIps, ",")
			r.RemoteAddr = ipArray[0]
		}
		if r.RemoteAddr == "" || strings.EqualFold("unknown", realIps) {
			r.RemoteAddr = r.Header.Get("Proxy-Client-IP")
		}
		if r.RemoteAddr == "" || strings.EqualFold("unknown", realIps) {
			r.RemoteAddr = r.Header.Get("WL-Proxy-Client-IP")
		}
		if r.RemoteAddr == "" || strings.EqualFold("unknown", realIps) {
			r.RemoteAddr = r.Header.Get("HTTP_CLIENT_IP")
		}
		if r.RemoteAddr == "" || strings.EqualFold("unknown", realIps) {
			r.RemoteAddr = r.Header.Get("HTTP_X_FORWARDED_FOR")
		}
		if r.RemoteAddr == "" || strings.EqualFold("unknown", realIps) {
			r.RemoteAddr = r.Header.Get("X-Real-IP")
		}
	}
	return r.RemoteAddr
}

func GetNetV4() string {
	response, errClient := http.Get("https://ipv4.netarm.com")
	if errClient != nil {
		return ""
	}
	defer response.Body.Close()
	body, _ := ioutil.ReadAll(response.Body)
	return string(body)
}

func GetNetV6() string {
	response, errClient := http.Get("https://ipv6.netarm.com")
	if errClient != nil {
		return ""
	}
	defer response.Body.Close()
	body, _ := ioutil.ReadAll(response.Body)
	return string(body)
}
